from django.http import HttpResponseRedirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render, get_object_or_404,Http404
from django.contrib import messages
from django.db.models import Q
from .forms import PostForm
from .models import Post


# Create your views here.
def add_stuff(request):
	if request.user.is_authenticated():
		form = PostForm(request.POST or None, request.FILES or None)
		if form.is_valid():
			instance = form.save(commit=False)
			instance.user = request.user
			instance.save()
			messages.success(request, "添加成功")
			return HttpResponseRedirect('/')
		context = {
			"form": form,
		}
	else:
		messages.info(request, "请先登录")
		return HttpResponseRedirect('/../accounts/login')	
	return render(request, 'posts/add_stuff.html', context)

def stuff_detail(request, id=None):
	instance = get_object_or_404(Post, id=id)
	context = {
		"detail": instance,
	}
	return render(request, 'posts/stuff_detail.html', context)

def stuff_list(request):
	queryset_list = Post.objects.all()
	query = request.GET.get("q")
	if query:
		queryset_list = queryset_list.filter(
				Q(name__icontains=query)|
				Q(price__icontains=query)
				).distinct()
	paginator = Paginator(queryset_list, 9) # Show 25 contacts per page
	page = request.GET.get('page')
	try:
		queryset = paginator.page(page)
	except PageNotAnInteger:
		# If page is not an integer, deliver first page.
		queryset = paginator.page(1)
	except EmptyPage:
		# If page is out of range (e.g. 9999), deliver last page of results.
		queryset = paginator.page(paginator.num_pages)
	context = {
		'stuff_list': queryset,
	}
	return render(request, 'posts/stuff_list.html', context)	

def stuff_update(request, id=None):
	if request.user.is_authenticated():
		instance = get_object_or_404(Post, id=id)
		form = PostForm(request.POST or None, request.FILES or None, instance=instance)
		if form.is_valid():
			instance = form.save(commit=False)
			instance.save()
			messages.success(request, "更新成功")
			return HttpResponseRedirect('/')
		context = {
			"form": form,
			"instance": instance,
		}
	else:
		messages.info(request, "请先登录")
		return HttpResponseRedirect('/../accounts/login')	
	return render(request, 'posts/add_stuff.html', context)

def stuff_delete(request):
	return render(request, 'posts/stuff_delete.html', {})			